// pages/my/my.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    telphone: '',
    name: '',
    studentID: '',
    imgSrc: '',
    userID: '',
    // 评价
    evaluate: true,
    // 收藏
    collect: false,
    // 兼职
    work: false,
    // 评论数据
    comment: [],
    collectedStores:[],
    collected: false,
    collectedId: []
  },
  // 点击评论跳转到详情页面
  tapComment(e) {
    wx.navigateTo({
      url: `/pages/commentDetails/commentDetails?id=${this.data.comment[e.currentTarget.id]._id}&userTelphone=${this.data.comment[e.currentTarget.id].userTelphone}&username=${this.data.name}&headImage=${this.data.imgSrc}`
    })
  },
    //点击修改昵称
    updateName(){
      wx.showActionSheet({
        itemList:['修改昵称'],
        success:(res)=>{
          wx.showModal({
            title:'修改昵称',
            placeholderText:'请输入修改后的昵称',
            editable:true,
            success:(e)=>{
              if(e.confirm&&e.content!=''){
                let db = wx.cloud.database()
                db.collection('CR_user').doc(this.data.userID).update({
                  data:{
                    username:e.content
                  },
                  success:(e)=>{
                    wx.showToast({
                      title: '修改成功',
                    })
                    this.getuser()
                  }
                })
              }
            }
          })
        }
      })
    },
  // 长按评论事件
  longtapComment(e) {
    let _that = this
    const db = wx.cloud.database()
    wx.showActionSheet({
      itemList: ['删除第' + (parseInt(e.currentTarget.id) + 1) + '条评价'],
      success: (result) => {
        if (result.tapIndex == 0) {
          wx.showModal({
            cancelColor: '#323c59',
            cancelText: '取消',
            confirmColor: '#f44141',
            confirmText: '确定',
            showCancel: true,
            title: '是否删除第' + (parseInt(e.currentTarget.id) + 1) + '条评价?',
            success: (result) => {
              if (result.confirm) {
                if(this.data.comment[e.currentTarget.id].imgPathID.length == 0){
                  db.collection('CR_comments').doc(_that.data.comment[e.currentTarget.id]._id).remove({
                    success(res) {
                         // 刷新页面
                         _that.getMyComment()
                      wx.showToast({
                        title: '删除成功！',
                        icon: 'success'
                      })
                   
                    },
                    fail:(e)=>{
                      wx.showToast({
                        title: '服务器繁忙，请稍后再试！',
                        icon: 'none'
                      })
                    }
                  })
                }else{
                  wx.cloud.deleteFile({
                    fileList: _that.data.comment[e.currentTarget.id].imgPathID
                  })
                  db.collection('CR_comments').doc(_that.data.comment[e.currentTarget.id]._id).remove({
                    success(res) {
                        // 刷新界面
                        _that.getMyComment()
                      wx.showToast({
                        title: '删除成功！',
                        icon: 'success'
                      })
                    
                    },
                    fail:(e)=>{
                      wx.showToast({
                        title: '服务器繁忙，请稍后再试！',
                        icon: 'none'
                      })
                    }
                  })
                }
            
              }
            }
          })
        }
      },
    })
  },
  // 获取我的评论数据
  getMyComment() {
    const db = wx.cloud.database()
    db.collection('CR_comments').where({
      userTelphone: this.data.telphone
    }).get({
      success: (res) => {
        this.setData({
          comment: res.data
        })
      }
    })
  },
  //退出登录
  outLogin(e) {
    wx.showModal({
      content: '你确定退出吗？',
      confirmText: '确定',
      confirmColor: 'red',
      cancelText: '取消',
      title: '提示',
      success: (res) => {
        if (res.confirm) {
          wx.clearStorageSync()
          wx.redirectTo({
            url: '/pages/login/login'
          })
        }
      }
    })
  },
  // 点击评价事件监听
  evaluate() {
    this.setData({
      evaluate: true,
      collect: false,
      work: false
    })
  },
  // 点击收藏事件监听
  collect() {
    this.setData({
      collect: true,
      evaluate: false,
      work: false
    })
  },
  // 点击工作事件监听
  work() {
    this.setData({
      collect: false,
      evaluate: false,
      work: true
    })
  },
      //获取头像
  getheadImage() {
    //获取本地数据
    let tel = wx.getStorageSync('Tel')
    this.setData({
      telphone: tel
    })
    //获取数据库数据
    let db = wx.cloud.database()
    db.collection('CR_user').where({
      telphone: this.data.telphone
    }).get({
      success: (res) => {
        this.setData({
          imgSrc: res.data[0].headImage
        })
      }
    })
  },
  //上传头像
  chooseImage() {
    wx.showActionSheet({
      itemList:['查看头像','修改头像'],
      success:(res)=>{
       if(res.tapIndex==1){
    wx.chooseImage({
      count: 1,
      success: (res) => {
        //上传
        wx.cloud.uploadFile({
          cloudPath: 'CR_userHeadImg/' + this.data.telphone + 'headImg.png',
          filePath: res.tempFilePaths[0],
          success: (e) => {
            if(this.data.imgSrc.length==0){
              //获取数据库数据
             let db = wx.cloud.database()
             console.log(this.data.userID);
             console.log(e.fileID);
             db.collection('CR_user').doc(this.data.userID).update({
               data:{
                 headImage:e.fileID
               }
             })
           }
            wx.showModal({
              confirmText: '确定',
              content: '已提交，正在审核中！',
              title: '提示',
              success: (result) => {},
              fail: (res) => {},
              complete: (res) => {},
            })
          }
        })
      }
    })
  }else if(res.tapIndex==0){
    let img = []
    img.push(this.data.imgSrc)
    wx.previewImage({
      urls: img,
    })
  }
  }
})
  },
  // 点击跳转到店铺页面
  toStoreDetail(e){
    wx.navigateTo({
      url: '/pages/stores/stores?storeName='+e.currentTarget.dataset.item.storeName
    })
  },
  // 获取收藏的店铺
  yunGetCollected() {
    let db = wx.cloud.database()
    let that = this
    db.collection('CR_stores')
      .get({
        success: (res) => {
          let user = wx.getStorageSync('Tel')
          let stores = res.data
          let collectedStore = []
          let collectedStoreId = []
          for (let i = 0; i < stores.length; i++) {
            let arr = stores[i].collected.filter(function (item) {
              return item == user
            })
            let idx = this.data.collectedId.indexOf(stores[i]._id)
            if (arr[0] == user && idx == -1) {
              collectedStoreId.push(stores[i]._id)
              collectedStore.push(stores[i])
            }
          }
          if (collectedStore[0]) {
            wx.setStorageSync('collecteds', collectedStore)
            let collecteds = wx.getStorageSync('collecteds')
            this.setData({collectedStores:collecteds.reverse()})
          }else{
            this.setData({collectedStores:[]})
          }
        }
      })
  },
  //获取用户信息
  getuser(){
    //获取本地数据
    let tel = wx.getStorageSync('Tel')
    this.setData({
      telphone: tel
    })
    //获取数据库数据
    let db = wx.cloud.database()
    db.collection('CR_user').where({
      telphone: this.data.telphone
    }).get({
      success: (res) => {
        this.setData({
          name: res.data[0].username,
          studentID: res.data[0].studentID,
          userID: res.data[0]._id,
          imgSrc: res.data[0].headImage,
        })
      }
    })
},
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
 //获取用户信息
 this.getuser()
    setTimeout(() => {
      this.getheadImage()
    }, 1000)
    // 获取我的评论数据
    this.getMyComment()
    //获取我的收藏数据
    this.yunGetCollected()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    
  },
  
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    wx.reLaunch({
      url: '/pages/my/my'
    })
    this.onShow()
    wx.showToast({
      title: '刷新成功！',
      icon: 'none'
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})